package gruppe7.servlets;

import gruppe7.data.User;
import gruppe7.data.UserController;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginCheckUser extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("pw");
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.jsp");
        UserController uc = UserController.getInstance();

        boolean userOk = uc.doLogin(request, username, password);

        if (userOk) {

            request.setAttribute("login", "true");

            String remUsername = (String) request.getParameter("remUser");

            if (!(remUsername == null)) {
                addCookie(request, response);
            }

            User user = uc.getSessionUser(request);
            if (user.isAdminUser()) {
                response.sendRedirect("/gruppe7/EditStationInfo");
            } else {
                response.sendRedirect("/gruppe7/");
            }
        } else {
            request.setAttribute("login", "false");
            rd.forward(request, response);
        }
    }

    private void addCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie userName = new Cookie("Trainstationusername", (String) request.getParameter("username"));

        userName.setMaxAge(60 * 60 * 24 * 7);
        response.addCookie(userName);
        String remPw = (String) request.getParameter("remPw");

        if (!(remPw == null)) {
            Cookie password = new Cookie("Trainstationpw", (String) request.getParameter("pw"));
            password.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(password);
        }





    }
}
	